package controllers

import (
	"encoding/json"
	"github.com/astaxie/beego"
	"strconv"
	"strings"
	"yunshangxiaozhao/models"
)

// Operations about Company
type CompanyController struct {
	beego.Controller
}

func (c *CompanyController) RetData(resp map[string]interface{}) {
	c.Data["json"] = resp
	c.ServeJSON()
}

// @Title AddCompany
// @Description add company
// @Param body	body	models.Company	true	"body for company content"
// @Success 200 {int} models.Company.Id
// @Failure 400 body is empty
// @Failure 403 add company but error
// @router /add [post]
func (c *CompanyController) AddCompany() {
	var company models.Company
	resp := make(map[string]interface{})
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &company)
	if err != nil {
		c.Abort("JsonToObjectFail")
	}
	err = models.AddCompany(&company)
	if err != nil {
		c.Abort("AddDataFail")
	} else {
		resp["code"] = 200
		resp["msg"] = "添加公司成功"
		resp["company_id"] = company.Id
	}
	c.RetData(resp)
}

// @Title GetCompany
// @Description 获取公司简介（P10）
// @Param	id	path	int	true	"The id of company"
// @Success 200 {object} models.Company
// @Failure 400 :body is empty
// @router /:id [get]
func (c *CompanyController) GetCompany() {
	resp := make(map[string]interface{})
	var id, err = c.GetInt(":id")
	if err != nil {
		c.Abort("ParamIsEmpty")
	}
	company, err := models.GetCompanyById(id)
	if err != nil {
		c.Abort("GetDataFail")
	} else {
		resp["code"] = 200
		resp["data"] = company
		resp["msg"] = "获取公司数据成功"
	}
	c.RetData(resp)
}

// @Title GetCompanyList
// @Description 企业列表查询接口by page and limit(P02)
// @Param	page	query 	int	true	"The page of company table(the index start with 0)"
// @Param	limit	query 	int	true	"The limit number of company table"
// @Success 200 {object} models.Company
// @Failure 400 :body is empty
// @router 	/query [get]
func (c *CompanyController) GetCompanyList() {
	resp := make(map[string]interface{})
	page, err1 := c.GetInt("page")
	limit, err2 := c.GetInt("limit")
	if err2 != nil || err1 != nil {
		c.Abort("ParamIsEmpty")
	}
	list, err := models.GetCompanyList(page, limit)
	list, err = models.GetCompanyListJob(list)
	list, err = models.GetCompanyListLive(list)
	if err != nil {
		c.Abort("GetDataFail")
	} else {
		resp["code"] = 200
		resp["data"] = list
		resp["msg"] = "获取公司数据成功"
	}
	c.RetData(resp)
}

// @Title GetWelfareCondition
// @Description 企业条件搜索福利接口(P05)
// @Success 200 {object} models.Welfare
// @Failure 400 :body is empty
// @router 	/condition/welfare [get]
func (c *CompanyController) GetWelfareCondition() {
	resp := make(map[string]interface{})
	list, err := models.GetWelfareList()
	if err != nil {
		c.Abort("GetDataFail")
	} else {
		resp["code"] = 200
		resp["data"] = list
		resp["msg"] = "获取福利条件成功"
	}
	c.RetData(resp)
}

// @Title GetCompanyListByCondition
// @Description 企业列表按条件查询接口by page and limit(P03-P07)
// @Param	page	query 	int	true	"The page of company table(the index start with 0)"
// @Param	limit	query 	int	true	"The limit number of company table"
// @Param	jobs	query	string	false	"岗位(split by ;)"
// @Param	locations	query	string	false	"企业位置(split by ;)"
// @Param	jobType	query	int	false	"岗位性质（全职=1 and 实习==0）"
// @Param	salaryMax	query	int	false	"最大薪资"
// @Param	salaryMin	query	int	false	"最小薪资"
// @Param	welfare		query	string	false "公司福利(split by ;)"
// @Param	types	query	string false "公司标签(split by ;)(0-国有企业 1-事业单位 2-政府组织 3-外商独资 4-中外合资 5-股份制企业 6-民营企业)"
// @Param	ranks	query	string false	"公司排行(split by ;)(0-世界500 1-中国500 2-上市公司 3-民企500 4-行业100 5-县市前10)"
// @Param	size	query	int	false	"公司规模(0:0-200;1:200-500;2:500-100;3:1000-5000;4:5000人以上)"
// @Param	categories	query	string	false	"行业分类(split by ;)(0-互联网 1-金融 2-生产制造 3-房地产 4-能源矿产 5-商业服务 6- 服务业 7-消费品 8-文化/传媒/娱乐/体育 9-政府/非盈利 10-交通/运输/物流 11-农业/林业/牧业/渔业 11-其他)"
// @Param	order	query	int	false	"排序（0-单位标签 1-工作城市 2-直播在线 3-单位规模 4-月度薪资 5-求职岗位）"
// @Success 200 {object} models.Company
// @Failure 400 :body is empty
// @router 	/query/condition [get]
func (c *CompanyController) GetCompanyListByCondition() {
	resp := make(map[string]interface{})
	page, err1 := c.GetInt("page")
	limit, err2 := c.GetInt("limit")
	if err2 != nil || err1 != nil {
		c.Abort("ParamIsEmpty")
	}
	userId := c.getUserIdFromSession()
	jobs := c.GetString("jobs")
	locations := c.GetString("locations")
	welfare := c.GetString("welfare")
	jobType, err := c.GetInt("jobType")
	if err != nil {
		jobType = -1
	}
	salaryMax, err := c.GetInt("salaryMax")
	if err != nil {
		salaryMax = -1
	}
	salaryMin, err := c.GetInt("salaryMin")
	if err != nil {
		salaryMin = -1
	}
	types := c.GetString("types")
	ranks := c.GetString("ranks")
	size, err := c.GetInt("size")
	if err != nil {
		size = -1
	}
	categories := c.GetString("categories")
	order, err := c.GetInt("order")
	if err != nil {
		order = -1
	}
	var jobList, locationList, welfareList []string
	var typeList, rankList, categoryList []int
	if jobs != "" {
		jobList = strings.Split(jobs, ";")
	}
	if locations != "" {
		locationList = strings.Split(locations, ";")
	}
	if welfare != "" {
		welfareList = strings.Split(welfare, ";")
	}
	if types != "" {
		for _, i := range strings.Split(types, ";") {
			num, _ := strconv.Atoi(i)
			typeList = append(typeList, num)
		}
	}
	if ranks != "" {
		for _, i := range strings.Split(ranks, ";") {
			num, _ := strconv.Atoi(i)
			rankList = append(rankList, num)
		}
	}
	if categories != "" {
		for _, i := range strings.Split(categories, ";") {
			num, _ := strconv.Atoi(i)
			categoryList = append(categoryList, num)
		}
	}
	list, err := models.GetCompanyListByCondition(jobList, locationList, jobType, salaryMax, salaryMin, welfareList, typeList, rankList, size, categoryList, order, page, limit)
	list, err = models.GetCompanyListJob(list)
	list, err = models.GetCompanyListLive(list)
	starList := models.GetCompanyListStar(list, userId)
	if err != nil {
		c.Abort("GetDataFail")
	} else {
		resp["code"] = 200
		resp["data"] = starList
		resp["msg"] = "获取公司数据成功"
	}
	c.RetData(resp)
}

// @Title GetCompanyListByKeyword
// @Description 企业搜索接口（P02）
// @Param	keyword	query	string	true	"The keyword to search"
// @Param	page	query 	int	true	"The page of company table(the index start with 0)"
// @Param	limit	query 	int	true	"The limit number of company table"
// @Success 200 {object} models.Company
// @Failure 400 :body is empty
// @router 	/search [get]
func (c *CompanyController) GetCompanyListByKeyword() {
	resp := make(map[string]interface{})
	page, err1 := c.GetInt("page")
	limit, err2 := c.GetInt("limit")
	keyword := c.GetString("keyword")
	if err2 != nil || err1 != nil {
		c.Abort("ParamIsEmpty")
	}
	if keyword == "" {
		c.Abort("InvalidSearch")
	}
	list, err := models.GetCompanyListByKeyword(keyword, page, limit)
	list, err = models.GetCompanyListJob(list)
	list, err = models.GetCompanyListLive(list)
	if err != nil {
		c.Abort("GetDataFail")
	} else if len(list) == 0 {
		if page == 0 {
			c.Abort("SearchReturnNull")
		} else {
			c.Abort("PageOutOfRange")
		}
	} else {
		resp["code"] = 200
		resp["data"] = list
		resp["msg"] = "获取公司数据成功"
	}
	c.RetData(resp)
}

// @Title AddCompanyDescription
// @Description 添加公司描述
// @Param body	body	models.CompanyDescription	true	"body for company description content"
// @Success 200 {int} models.CompanyDescription.Id
// @Failure 400 body is empty
// @router /description/add [post]
func (c *CompanyController) AddCompanyDescription() {
	var description models.CompanyDescription
	resp := make(map[string]interface{})
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &description)
	if err != nil {
		c.Abort("JsonToObjectFail")
	}
	companyId := c.getCompanyIdFromSession()

	company, err := models.GetCompanyById(companyId)
	if err != nil {
		c.Abort("GetDataFail")
	}
	description.Company = company
	err = models.AddCompanyDescription(&description)
	if err != nil {
		c.Abort("AddDataFail")
	} else {
		resp["code"] = 200
		resp["msg"] = "添加公司描述成功"
		resp["company_description_id"] = description.Id
	}
	c.RetData(resp)
}

// @Title GetCompanyDescriptionListByCompanyId
// @Description 获取公司描述列表（P13）
// @Param	company_id	path	int	true	"The id of company"
// @Success 200 {object} models.CompanyDescription
// @Failure 400 :body is empty
// @router /:company_id/description [get]
func (c *CompanyController) GetCompanyDescriptionListByCompanyId() {
	resp := make(map[string]interface{})
	var id, err = c.GetInt(":company_id")
	if err != nil {
		c.Abort("ParamIsEmpty")
	}
	company, err := models.GetCompanyDescriptionByCompanyId(id)
	if err != nil {
		c.Abort("GetDataFail")
	} else {
		resp["code"] = 200
		resp["data"] = company
		resp["msg"] = "获取公司数据成功"
	}
	c.RetData(resp)
}

// @Title CompanyLogin
// @Description 企业用户登陆接口
// @Param body	body	models.CompanyAccount	true	"Company login with username and password"
// @Success 200 {string} login success
// @Failure 400 user not exist
// @router /login [post]
func (c *CompanyController) CompanyLogin() {
	resp := make(map[string]interface{})
	var account = new(models.CompanyAccount)
	err := json.Unmarshal(c.Ctx.Input.RequestBody, account)
	account.Status = true
	if err != nil {
		c.Abort("ParamIsEmpty")
	}
	account, err = models.CompanyLogin(account)
	if err != nil || account.Id == 0 {
		c.Abort("LoginFailed")
	} else {
		c.SetSession("accountId", account.Id)
		c.SetSession("companyId", account.Company.Id)
		c.SetSession("userId", -1)
		resp["code"] = 200
		resp["msg"] = "登录成功"
		resp["account_id"] = account.Id
		resp["company_id"] = account.Company.Id
	}
	c.RetData(resp)
}

// @Title AddCompanyJob
// @Description add company job
// @Param body	body	models.CompanyJob	true	"body for company job content"
// @Success 200 {int} models.CompanyJob.Id
// @Failure 400 body is empty
// @router /job/add [post]
func (c *CompanyController) AddCompanyJob() {
	var job models.CompanyJob
	resp := make(map[string]interface{})
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &job)
	if err != nil {
		c.Abort("JsonToObjectFail")
	}
	companyId := c.getCompanyIdFromSession()

	company, err := models.GetCompanyById(companyId)
	if err != nil {
		c.Abort("GetDataFail")
	}
	job.Company = company
	err = models.AddCompanyJob(&job)
	if err != nil {
		println(err.Error())
		c.Abort("AddDataFail")
	} else {
		resp["code"] = 200
		resp["msg"] = "添加公司职位成功"
		resp["company_job_id"] = job.Id
	}
	c.RetData(resp)
}

// @Title GetCompanyJobList
// @Description 获取公司招聘岗位（P08）
// @Param	company_id	path	int	true	"The id of company"
// @Success 200 {object} models.CompanyJob
// @Failure 400 :body is empty
// @router /:company_id/job [get]
func (c *CompanyController) GetCompanyJobByCompanyId() {
	resp := make(map[string]interface{})
	var id, err = c.GetInt(":company_id")
	if err != nil {
		c.Abort("ParamIsEmpty")
	}
	job, err := models.GetCompanyJobByCompanyId(id)
	if err != nil {
		c.Abort("GetDataFail")
	} else {
		resp["code"] = 200
		resp["data"] = job
		resp["msg"] = "获取工作数据成功"
	}
	c.RetData(resp)
}

// @Title GetCompanyJob
// @Description get company job by id
// @Param	id	path	int	true	"The id of job"
// @Success 200 {object} models.CompanyJob
// @Failure 400 :body is empty
// @router /job/:id [get]
func (c *CompanyController) GetCompanyJobById() {
	resp := make(map[string]interface{})
	var id, err = c.GetInt(":id")
	if err != nil {
		c.Abort("ParamIsEmpty")
	}
	job, err := models.GetCompanyJobById(id)
	if err != nil {
		c.Abort("GetDataFail")
	} else {
		resp["code"] = 200
		resp["data"] = job
		resp["msg"] = "获取工作数据成功"
	}
	c.RetData(resp)
}

// @Title AddCompanyAccount
// @Description 注册
// @Param Username formData string "username" true "用户名"
// @Param Password formData string "password" true "密码"
// @Param CheckPassword formData string "checkPassword" true "确认密码"
// @Param CompanyName formData string "companyName" true "企业名称"
// @Success 200 {int} models.CompanyAccount.Id
// @Failure 400 body is empty
// @router /account/register [post]
func (c *CompanyController) AddCompanyAccount() {

	resp := make(map[string]interface{})
	req := make(map[string]interface{})
	_ = json.Unmarshal(c.Ctx.Input.RequestBody, &req)

	username := c.GetString("Username")
	password := c.GetString("Password")
	checkPassword := c.GetString("CheckPassword")
	name := c.GetString("CompanyName")
	var company = new(models.Company)
	company.Status = true
	company.Name = name
	err := models.AddCompany(company)
	if err != nil {
		println(err.Error())
		c.Abort("AddDataFail")
	}
	if password == "" || username == "" || checkPassword == "" {
		c.Abort("ParamIsEmpty")
	}
	if password != checkPassword {
		c.Abort("PasswordNotSame")
	}
	var account = new(models.CompanyAccount)
	account.Username = username
	account.Password = password
	account.Company = company
	account.Status = true

	account, err = models.CompanyAccountCheck(account)
	err = models.CompanyRegister(account)
	if err != nil {
		println(err.Error())
		c.Abort("AddDataFail")
	} else {
		resp["code"] = 200
		resp["msg"] = "注册成功"
		resp["company_description_id"] = account.Id
	}
	c.RetData(resp)
}

// @Title BindCompanyAccount
// @Description 绑定公司账户
// @Param CompanyName formData string "公司名字" true "用户名"
// @Success 200 {int} models.CompanyAccount.Id
// @Failure 400 body is empty
// @router /account/bind [post]
func (c *CompanyController) BindCompanyAccount() {
	accountId := c.getAccountIdFromSession()
	resp := make(map[string]interface{})
	req := make(map[string]interface{})
	_ = json.Unmarshal(c.Ctx.Input.RequestBody, &req)

	companyName := c.GetString("CompanyName")

	if companyName == "" {
		c.Abort("ParamIsEmpty")
	}
	companyAccount, err := models.GetCompanyAccountById(accountId)
	if err != nil {
		c.Abort("GetDataFail")
	}
	companyAccount.Company, err = models.GetCompanyByName(companyName)
	if err != nil {
		c.Abort("GetDataFail")
	}
	err = models.UpdateCompanyAccount(companyAccount)
	if err != nil {
		println(err.Error())
		c.Abort("UpdateDataFail")
	} else {
		resp["code"] = 200
		resp["msg"] = "绑定成功"
	}
	c.RetData(resp)
}

// api for web

// @Title GetCompanyInterview
// @Description get company interview with user
// @Param	id	path	int	true	"The id of job"
// @Success 200 {object} models.CompanyJob
// @Failure 400 :body is empty
// @router /interview/:id [get]
func (c *CompanyController) GetCompanyInterview() {
	resp := make(map[string]interface{})
	page, err1 := c.GetInt("page")
	limit, err2 := c.GetInt("limit")
	if err2 != nil || err1 != nil {
		c.Abort("ParamIsEmpty")
	}
	var id, err = c.GetInt(":id")
	if err != nil {
		c.Abort("ParamIsEmpty")
	}
	data, err := models.GetCompanyInterviewWithNumById(id, page, limit)

	if err != nil {
		c.Abort("GetDataFail")
	} else {
		resp["code"] = 200
		resp["data"] = data
		resp["msg"] = "获取公司职位发布数据成功"
	}
	c.RetData(resp)
}

// @Title UpdateCompanyDesc
// @Description 更新公司介绍
// @Param Name formData	string true	"集团/公司名称"
// @Param Address formData string true "所在城市"
// @Param Type formData string true "标签"
// @Param Property formData string true "属性"
// @Param Size formData int true "单位规模"
// @Param Category formData int true "行业分类"
// @Success 200 {object} models.CompanyJob
// @Failure 400 :body is empty
// @router /desc [put]
func (c *CompanyController) UpdateCompanyDesc() {
	resp := make(map[string]interface{})
	var company models.Company
	if err := c.ParseForm(&company); err != nil {
		c.Abort("JsonToObjectFail")
	}

	company.Id = c.getCompanyIdFromSession()
	err := models.UpdateCompanyDesc(company)
	if err != nil {
		c.Abort("UpdateDataFail")
	}

	resp["msg"] = "更新公司介绍成功"
	resp["code"] = 200
	c.RetData(resp)
}

// @Title UpdateCompanyJob
// @Description 更新公司岗位备注
// @Param Id formData	string true	"岗位id"
// @Param Note formData string true "备注"
// @Success 200 {object} models.CompanyJob
// @Failure 400 :body is empty
// @router /job/note [put]
func (c *CompanyController) UpdateCompanyJob() {
	resp := make(map[string]interface{})
	var job models.CompanyJob
	if err := c.ParseForm(&job); err != nil {
		c.Abort("JsonToObjectFail")
	}

	err := models.UpdateCompanyJobNote(&job)
	if err != nil {
		c.Abort("UpdateDataFail")
	}

	resp["msg"] = "更新公司岗位备注成功"
	resp["code"] = 200
	c.RetData(resp)
}

// @Title UpdateCompanyJob
// @Description 更新公司岗位备注
// @Param Id formData	string true	"Resume/Interview id"
// @Param Note formData string true "备注"
// @Param Type formData string true "0: resume_put, 1: company_interview"
// @Success 200 {object} models.CompanyJob
// @Failure 400 :body is empty
// @router /note [put]
func (c *CompanyController) UpdateNote() {
	resp := make(map[string]interface{})
	Id, err := c.GetInt("Id")
	Note := c.GetString("Note")
	t, err := c.GetInt("Type")

	err = models.UpdateInterviewOrResumeNote(Id, Note, t)
	if err != nil {
		c.Abort("UpdateDataFail")
	}

	resp["msg"] = "更新备注成功"
	resp["code"] = 200
	c.RetData(resp)
}

// @Title UpdateResult
// @Description 公司更新结果(0: 拒绝该用户 1: 接受该用户)
// @Param Id body string true "Interview id"
// @Param Result body int true "status company want resume to enter(2-接受一面 3-接受二面 4-提供offer)"
// @Param ResultType body int true "结果类型(0-拒绝 1-同意)"
// @Success 200 {object} models.CompanyJob
// @Failure 400 :body is empty
// @router /interview [put]
func (c *CompanyController) UpdateResult() {
	var interview models.CompanyInterview
	resp := make(map[string]interface{})
	if err := c.ParseForm(&interview); err != nil {
		c.Abort("JsonToObjectFail")
	}

	err := models.UpdateCompanyInterviewByCompany(interview)
	if err != nil {
		c.Abort("UpdateDataFail")
	} else {
		resp["code"] = 200
		resp["msg"] = "更新用户简历状态成功"
	}

	c.RetData(resp)
}

// 获取已发布岗位招聘情况(海选库,一面,二面,签约)
// @Title GetEmployGroupByJobName
// @Description 招聘管理-首页(P3)
// @Param	page	query 	int	true	"The page of company table(the index start with 0)"
// @Param	limit	query 	int	true	"The limit number of company table"
// @Param	keyword query	string	true	"keyword for search"
// @Success 200 {object} models.JobInterviewWithArea
// @Failure 400 :body is empty
// @router /job/group [get]
func (c *CompanyController) GetEmployGroupByJobName() {
	resp := make(map[string]interface{})

	limit, page := c.getLimitAndPage()
	keyword := c.GetString("keyword")
	companyId := c.getCompanyIdFromSession()
	data, err := models.GetEmployGroupByJobName(companyId, page, limit, keyword)

	if err != nil {
		c.Abort("GetDataFail")
	} else if len(data) == 0 {
		if page == 0 {
			c.Abort("ContentIsNull")
		} else {
			c.Abort("PageOutOfRange")
		}
	} else {
		resp["code"] = 200
		resp["data"] = data
		resp["msg"] = "获取公司职位发布数据成功"
	}
	c.RetData(resp)
}

// @Title GetEmployInformationByJobName
// @Description 招聘管理-首页(P4)
// @Param	name	query	string	true	"The name of job"
// @Param	page	query 	int	true	"The page of company table(the index start with 0)"
// @Param	limit	query 	int	true	"The limit number of company table"
// @Param	keyword query	string	false	"keyword for search"
// @Success 200 {object} models.JobInterviewWithArea
// @Failure 400 :body is empty
// @router /job/city [get]
func (c *CompanyController) GetEmployInformationByJobName() {
	resp := make(map[string]interface{})

	limit, page := c.getLimitAndPage()
	name := c.GetString("name")
	keyword := c.GetString("keyword")
	companyId := c.getCompanyIdFromSession()
	data, err := models.GetEmployInformationByJobName(name, companyId, page, limit, keyword)

	if err != nil {
		c.Abort("GetDataFail")
	} else if len(data) == 0 {
		if page == 0 {
			c.Abort("ContentIsNull")
		} else {
			c.Abort("PageOutOfRange")
		}
	} else {
		resp["code"] = 200
		resp["data"] = data
		resp["msg"] = "获取公司职位发布数据成功"
	}
	c.RetData(resp)
}

// @Title GetUserInformationByJobName
// @Description 招聘管理-海选库(P4)
// @Param name query string true "The name of job"
// @Param city query string true "the city of job"
// @Param type query int true "type of interview(1-单选 2-双选 3-offer)"
// @Param keyword query string false "keyword for search"
// @Param	page	query 	int	true	"The page of company table(the index start with 0)"
// @Param	limit	query 	int	true	"The limit number of company table"
// @Success 200 {object} models.CompanyJob
// @Failure 400 :body is empty
// @router /user/city [get]
func (c *CompanyController) GetUserInformationByJobName() {
	resp := make(map[string]interface{})

	limit, page := c.getLimitAndPage()
	name := c.GetString("name")
	city := c.GetString("city")
	t, err := c.GetInt("type")
	keyword := c.GetString("keyword")
	companyId := c.getCompanyIdFromSession()
	data, err := models.GetUserInformationByJobName(name, city, t, companyId, page, limit, keyword)

	if err != nil {
		c.Abort("GetDataFail")
	} else if len(data) == 0 {
		if page == 0 {
			c.Abort("ContentIsNull")
		} else {
			c.Abort("PageOutOfRange")
		}
	} else {
		resp["code"] = 200
		resp["data"] = data
		resp["msg"] = "获取公司职位发布数据成功"
	}
	c.RetData(resp)
}

// @Title GetEmployNum
// @Description 获取岗位数(jobNum)-招聘人数(allNum)
// @Success 200 {object} models.JobInterviewWithArea
// @Failure 400 :body is empty
// @router /job/num [get]
func (c *CompanyController) GetEmployNum() {
	resp := make(map[string]interface{})

	companyId := c.getCompanyIdFromSession()
	jobNum, allNum, err := models.GetEmployNum(companyId)

	if err != nil {
		c.Abort("GetDataFail")
	} else {
		data := make(map[string]interface{})
		data["jobNum"] = jobNum
		data["allNum"] = allNum
		resp["code"] = 200
		resp["data"] = data
		resp["msg"] = "获取公司职位发布数据成功"
	}
	c.RetData(resp)
}

// @Title QueryResultByCompany
// @Description 公司查看 单选/双选/offer
// @Param	type	query 	int	true	"查看类型 -1: 全部 0: 拒绝 1: 单选 2: 双选 3: offer"
// @Param	page	query 	int	true	"The page number(the index start with 0)"
// @Param	limit	query 	int	true	"The limit number"
// @Success 200 {object} query success
// @Failure 400 user not login
// @router /employment [get]
func (c *CompanyController) QueryResultByCompany() {
	resp := make(map[string]interface{})
	userId := c.getUserIdFromSession()
	limit, page := c.getLimitAndPage()
	t, err := c.GetInt("type")
	if err != nil {
		c.Abort("ParamIsEmpty")
	}

	putAndInvite, err := models.QueryAllUserPutAndCompanyInviteByCompany(userId, t, page, limit)
	if err != nil {
		c.Abort("GetDataFail")
	}

	resp["data"] = putAndInvite
	resp["msg"] = "获取数据成功"

	c.RetData(resp)
}

// @Title UpdateResultByCompany
// @Description 公司更新 单选/双选/offer
// @Param jobId form int true "岗位id"
// @Param userId form int true "用户id"
// @Param answer form int true "0: 拒绝 1: 接受"
// @Success 200 {object} query success
// @Failure 400 user not login
// @router /employment [put]
func (c *CompanyController) UpdateResultByCompany() {
	resp := make(map[string]interface{})
	answer, err := c.GetInt("answer")
	jobId, err := c.GetInt("jobId")
	userId, err := c.GetInt("userId")
	if err != nil {
		c.Abort("ParamIsEmpty")
	}

	putAndInvite, err := models.QueryUserPutAndCompanyInvite(userId, jobId)
	if err != nil {
		c.Abort("")
	}
	putAndInvite.CompanyAnswer = answer
	err = models.UpdateUserPutAndCompanyInvite(putAndInvite, "company_answer")
	if err != nil {
		c.Abort("GetDataFail")
	}

	resp["data"] = putAndInvite
	resp["msg"] = "更新数据成功"

	c.RetData(resp)
}

// @Title InsertResultByCompany
// @Description 公司邀请用户
// @Param jobId form int true "岗位id"
// @Param userId form int true "用户id"
// @Param note form string false "备注"
// @Success 200 {object} query success
// @Failure 400 user not login
// @router /employment [post]
func (c *CompanyController) InsertResultByCompany() {
	resp := make(map[string]interface{})
	var putAndInvite models.UserPutAndCompanyInvite
	companyId := c.getCompanyIdFromSession()
	jobId, err := c.GetInt("jobId")
	userId, err := c.GetInt("userId")
	note := c.GetString("note")
	if err != nil {
		c.Abort("ParamIsEmpty")
	}

	putAndInvite.Company = &models.Company{Id: companyId}
	putAndInvite.Job = &models.CompanyJob{Id: jobId}
	putAndInvite.User = &models.User{Id: userId}
	putAndInvite.UserAnswer = 2
	putAndInvite.CompanyAnswer = 1
	putAndInvite.IsPut = false
	putAndInvite.Offer = 2
	putAndInvite.Note = note
	if err != nil {
		c.Abort("")
	}
	id, err := models.InsertUserPutAndCompanyInvite(putAndInvite)
	if err != nil {
		c.Abort("AddDataFail")
	}

	resp["data"] = id
	resp["msg"] = "邀请用户成功"

	c.RetData(resp)
}

// @Title SendOffer
// @Description 公司 发布 offer
// @Param jobId form int true "岗位id"
// @Param userId form int true "用户id"
// @Param answer form int true "0: 拒绝 1: 发offer"
// @Success 200 {object} query success
// @Failure 400 user not login
// @router /offer [post]
func (c *CompanyController) SendOffer() {
	resp := make(map[string]interface{})
	answer, err := c.GetInt("answer")
	jobId, err := c.GetInt("jobId")
	userId, err := c.GetInt("userId")
	if err != nil {
		c.Abort("ParamIsEmpty")
	}

	putAndInvite, err := models.QueryUserPutAndCompanyInvite(userId, jobId)
	if err != nil {
		c.Abort("")
	}
	putAndInvite.Offer = answer
	err = models.UpdateUserPutAndCompanyInvite(putAndInvite, "offer")
	if err != nil {
		c.Abort("GetDataFail")
	}

	resp["msg"] = "更新数据成功"

	c.RetData(resp)
}

// util-----------------------------------------------------------------
/*
 从 session 中获取公司 id
*/
func (c *CompanyController) getCompanyIdFromSession() int {
	id := c.GetSession("companyId")
	if id == nil {
		c.Abort("CompanyNotLogin")
	}

	return id.(int)
}

/*
 从 session 中获取账户 id
*/
func (c *CompanyController) getAccountIdFromSession() int {
	id := c.GetSession("accountId")
	if id == nil {
		c.Abort("CompanyNotLogin")
	}
	return id.(int)
}

/*
 从 session 中获取账户 user_id
*/
func (c *CompanyController) getUserIdFromSession() int {
	id := c.GetSession("userId")
	if id == nil {
		c.Abort("UserNotLogin")
	}
	return id.(int)
}

func (c *CompanyController) getLimitAndPage() (limit int, page int) {
	page, errPage := c.GetInt("page")
	limit, errLimit := c.GetInt("limit")
	if errLimit != nil || errPage != nil {
		c.Abort("ParamIsEmpty")
	}
	if page < 0 || limit < 0 {
		c.Abort("ReadParam")
	}

	return limit, page * limit
}
